

import { ref, Ref } from 'vue';
import { apiResult } from '../api/axiosConfig';

type optionsType<T> = {
  params: T;
  disableInitFetch?: boolean;
};
type requestCallBack<T = any> = {
  loading: Ref<boolean | undefined>;
  fetch: () => void;
  data: Ref<T | undefined>;
  result: Ref<apiResult<T> | undefined>;
  state: Ref<number | undefined>;
  message: Ref<string | undefined>;
  total: Ref<number | undefined>;
};

/**
 *
 * @param service 接口异步函数
 * @param params 函数参数
 * T：回调data的泛型
 * T2：param的泛型
 */
// eslint-disable-next-line no-unused-vars
 export const useRequest = <T = any, T2 = any>(service: (e: T2) => Promise<apiResult<T>>, options: optionsType<T2>): requestCallBack<T> => {
  const { params, disableInitFetch = false } = options;
  const loading = ref(false);
  const data = ref<T>();
  const state = ref<number>();
  const message = ref<string>();
  const total = ref<number>();
  const result = ref<apiResult<T> | undefined>();
  const fetch = async () => {
    loading.value = true;
    const res: apiResult<T> = (await service(params)) as unknown as apiResult<T>;
    data.value = res.data;
    result.value = res;
    state.value = res.state;
    message.value = res.message;
    total.value = res.total;
    loading.value = false;
  };
  if (!disableInitFetch) {
    fetch();
  }

  return {
    loading,
    fetch,
    data,
    result,
    state,
    message,
    total,
  };
};
 